using(['utils/fetchEnhancer', 'pc/js/utils/XForm'], function(fetch, XForm){

var doc = document;

var mailBtn = doc.getElementById('btn');
var editBtn = doc.getElementById('editbtn');
var f = new XForm();
var f2 = new XForm();

f.checkOther('account', {
    minLength: 6,
    infoText : '请输入注册时的邮箱',
    errorText : '邮箱不能为空'
});
f2.checkOther('code', {
    minLength: 4,
    infoText : '请输入验证码',
    errorText : '验证码不能对哦'
});
f2.checkOther('pwd', {
    minLength: 6,
    infoText : '请输入新密码',
    errorText : '密码至少 6 位哦'
});


var tickDown = function(x) {
    if(x < 1) {
        mailBtn.innerHTML = '重新获取验证码';
        mailBtn.disabled = false;

        return;
    }

    mailBtn.disabled = true;
    mailBtn.innerHTML = '获取中 ('+ x +')';

    setTimeout(function(){
        tickDown(x - 1);
    }, 1000);
};

mailBtn.onclick = function() {
    var valid = f.validate();

    if(!valid) {
        return;
    }

    var email = doc.getElementById('account').value;
    if(!f.rulesConfig.email.regular.test(email)) {
        return;
    }

    tickDown(30);
    fetch('/api/mail/sendfind', {
        method: 'POST',
        body: 'email=' + encodeURIComponent(email)

    }).then(function(res) {
        if(0 === res.status) {
            XUI.toast.success('验证码发送成功');
        } else {
            XUI.toast.error('验证码发送失败 ' + res.status);
        }
    });
};

editBtn.onclick = function() {
    var valid = f2.validate();

    if(!valid) {
        return;
    }

    var email = doc.getElementById('account').value;
    var code = doc.getElementById('code').value;
    var pwd = doc.getElementById('pwd').value;

    if(!f2.rulesConfig.email.regular.test(email)) {
        return;
    }

    fetch('/api/account/editpwdbymailcode', {
        method: 'POST',
        body: 'email=' + encodeURIComponent(email)
            + '&code=' + encodeURIComponent(code)
            + '&pwd=' + encodeURIComponent(pwd)

    }).then(function(res) {
        if(0 === res.status) {
            doc.getElementById('pwd').value = '';
            doc.getElementById('code').value = '';

            XUI.toast.success('修改成功');
        } else {
            XUI.toast.error('修改失败 ' + res.status);
        }
    });
};

});
